<template>
  <div class="app-container">
    <!-- 页头返回 -->
    <el-page-header 
      :icon="ArrowLeft" 
      @back="goBack"
      class="page-header"
    >
      <template #content>
        <el-row>
          <el-col :span="24">
            <el-input
              v-model="form.title"
              class="article-title"
              clearable
            />
          </el-col>
        </el-row>
      </template>
      <template #extra>
        <el-button type="primary" class="button-item" @click="handleAdd">发布文章</el-button>
      </template>
    </el-page-header>



    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      
      <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="form.content"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>



    <!-- 发布文章弹框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <!-- 表单 -->
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" border>
        <el-form-item label="文章标签" prop="tagIds">
          <el-select 
            v-model="form.tagIds"  
            multiple  
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="5"
            @change="handleTagChange"
            placeholder="最多5个标签"
          >
            <el-option
              v-for="tag in tagList"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章封面" prop="coverImage">
          <image-upload v-model="form.coverImage" :limit="imgNum"/>
        </el-form-item>
        <el-form-item label="文章摘要" prop="summary">
          <el-input
            v-model="form.summary"
            type="textarea"
            :rows="3"
            placeholder="摘要,自动获取文章内容前128个内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类专栏" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择"
            style="width: 100px;"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可见范围" prop="visibility">
          <el-radio-group v-model="form.visibility">
            <el-radio value="0">全部可见</el-radio>
            <el-radio value="1">仅我可见</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" style="border-radius: 20px;">取 消</el-button>
          <el-button type="primary" class="button-item" @click="submitForm">发布文章</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ArrowLeft } from '@element-plus/icons-vue'
import { getBlogArticles, addBlogArticles, updateBlogArticles } from "@/api/blog/blog_articles";
import { listBlogTags } from '@/api/blog/blog_tags';
import { listBlogCategories } from '@/api/blog/blog_categories';
import {loadAllParams} from '@/api/params'

import '@wangeditor/editor/dist/css/style.css' // 引入 css

import {onMounted, ref,  onBeforeUnmount, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadAPI } from '../../../api/common';


const { proxy } = getCurrentInstance();

const route = useRoute();
const form = ref({});
const formRef = ref();
const open = ref(false);
const title = ref('');
const imgNum = 1


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const mode = ref('simple') // mode: 'default', // 或 'simple'
const imageList1 = ref([])

//工具栏配置信息
const toolbarConfig = {}
const editorConfig = {
  MENU_CONF: {},
  }

editorConfig.MENU_CONF['uploadImage'] = {

    async customUpload(file, insertFn) {                   // JS 语法
    // file 即选中的文件
    // 自己实现上传，并得到图片 url alt href
    await uploadAPI(file).then(res => {
    // 最后插入图片
      insertFn(res.url, res.fileType, res.originalFilename)
    })

  },
    
}


    // 插入图片
  editorConfig.MENU_CONF['insertImage'] = {
      onInsertedImage(imageNode) {                    // JS 语法
      if (imageNode == null) return
      const { src, alt, url, href } = imageNode
      imageList1.value.push(src)

      //最后保存编辑器内容之前，使用 editor.getElemsByType('image') 获取当前编辑器的所有图片，记录为 imageList2
      // 对比 imageList1 和 imageList2 ，两者的差异，就是删除过的图片（处理服务器上的图片）


      console.log(valueHtml)
    },
  }
      
    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }
    



const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' }
  ],
  tagIds: [
    { required: true, message: '请选择文章标签', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请选择文章封面', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择分类专栏', trigger: 'change' }
  ],
  visibility: [
    { required: true, message: '请选择可见范围', trigger: 'change' }
  ]
};

/** 提交按钮 */
function submitForm() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateBlogArticles(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          goBack();
        });
      } else {
        addBlogArticles(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          goBack();
        });
      }
    } else {
      console.log('验证失败');
      return false;
    }
  });
}
// 标签选择器监听数量
const handleTagChange = (value) => {
  const maxTags = 5;
  if (value.length > maxTags) {
    // 移除最近选择的标签
    form.value.tagIds = value.slice(0, maxTags);
    // 或者提示用户
     proxy.$modal.msgError("仅能选择5个标签");
  }
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  // form.value = {
  //   id: null,
  //   title: null,
  //   content: null,
  //   summary: null,
  //   status: null,
  //   coverImage:"",
  //   userId: null,
  //   categoryId: null,
  //   views: null,
  //   likes: null,
  //   publishedTime: null,
  //   createBy: null,
  //   updateBy: null,
  //   createTime: null,
  //   updateTime: null,
    
  // };
}

function stripHtmlTags(html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || "";
}

const tagList = ref([]);
const categoryList = ref([])
// 发布文章
const handleAdd = () => {
 open.value= true;
 title.value = "发布文章";
 //截取form.content内容前128个字符
 if(form.value.content != null){
  form.value.summary = stripHtmlTags(form.value.content).substring(0, 128);
 }
  //获取标签列表
  listBlogTags(loadAllParams).then((res) => {
   tagList.value = res.rows;
  })
  //获取分类列表
  listBlogCategories(loadAllParams).then((res) => {
   categoryList.value = res.rows;
  })

}

const getArticle = () => {
  if(route.query.id){
    getBlogArticles(route.query.id).then(response => {
    form.value = response.data;
  });
  }

}

const goBack = () => {
  //通过router，返回到来时路由
  proxy.$router.go(-1);

}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

onMounted(() => {
  getArticle();
})

</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 15px;
}
.article-title{
  width:1000px;
  height: 40px;
  font-size: 20px;
}





</style>